<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 连接测试工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-control {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
        }
        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }
        .btn-danger {
            background-color: #f44336;
            color: white;
        }
        .btn-secondary {
            background-color: #2196F3;
            color: white;
        }
        .btn-warning {
            background-color: #ff9800;
            color: white;
        }
        .logs {
            height: 200px;
            overflow-y: auto;
            background-color: #f5f5f5;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: monospace;
        }
        .log-entry {
            margin-bottom: 5px;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        .log-entry.error { color: #f44336; }
        .log-entry.success { color: #4CAF50; }
        .log-entry.info { color: #2196F3; }
        .log-entry.warning { color: #ff9800; }
        h2 {
            color: #333;
            border-bottom: 2px solid #eee;
            padding-bottom: 10px;
        }
    </style>
</head>
<body>
    <h1>WebSocket 连接测试工具</h1>
    <p>用于测试WebSocket连接和消息发送的统一工具</p>
    
    <div class="container">
        <div class="card">
            <h2>连接设置</h2>
            <div class="form-group">
                <label for="wsUrl">WebSocket URL:</label>
                <input type="text" id="wsUrl" class="form-control" value="ws://localhost:8080/websocket" />
            </div>
            <div class="form-group">
                <label for="userId">用户ID:</label>
                <input type="text" id="userId" class="form-control" value="2" />
            </div>
            <div class="form-group">
                <label for="teamId">团队ID:</label>
                <input type="text" id="teamId" class="form-control" value="0" />
            </div>
            <div class="form-group">
                <label for="heartbeatInterval">心跳间隔 (毫秒):</label>
                <input type="number" id="heartbeatInterval" class="form-control" value="30000" />
            </div>
            <div>
                <button id="btnConnect" class="btn btn-primary">连接</button>
                <button id="btnDisconnect" class="btn btn-danger" disabled>断开</button>
                <button id="btnHeartbeat" class="btn btn-secondary" disabled>发送心跳</button>
                <button id="btnClearLogs" class="btn btn-warning">清空日志</button>
            </div>
        </div>

        <div class="card">
            <h2>私聊消息</h2>
            <div class="form-group">
                <label for="privateMsgTo">接收者ID:</label>
                <input type="text" id="privateMsgTo" class="form-control" value="1" />
            </div>
            <div class="form-group">
                <label for="privateMsg">消息内容:</label>
                <input type="text" id="privateMsg" class="form-control" value="你好，这是私聊测试消息" />
            </div>
            <button id="btnSendPrivate" class="btn btn-primary" disabled>发送私聊</button>
        </div>

        <div class="card">
            <h2>大厅聊天</h2>
            <div class="form-group">
                <label for="hallMsg">消息内容:</label>
                <input type="text" id="hallMsg" class="form-control" value="你好，这是大厅消息" />
            </div>
            <button id="btnSendHall" class="btn btn-primary" disabled>发送大厅消息</button>
        </div>

        <div class="card">
            <h2>团队聊天</h2>
            <div class="form-group">
                <label for="teamMsgTeamId">团队ID:</label>
                <input type="text" id="teamMsgTeamId" class="form-control" value="1" />
            </div>
            <div class="form-group">
                <label for="teamMsg">消息内容:</label>
                <input type="text" id="teamMsg" class="form-control" value="你好，这是团队消息" />
            </div>
            <button id="btnSendTeam" class="btn btn-primary" disabled>发送团队消息</button>
        </div>

        <div class="card">
            <h2>自定义JSON消息</h2>
            <div class="form-group">
                <label for="customJson">JSON内容:</label>
                <textarea id="customJson" class="form-control" rows="5">{
  "fromId": 2,
  "toId": 1,
  "text": "自定义JSON消息",
  "chatType": 1,
  "teamId": 0
}</textarea>
            </div>
            <button id="btnSendCustom" class="btn btn-primary" disabled>发送自定义消息</button>
        </div>

        <div class="card">
            <h2>日志</h2>
            <div id="logs" class="logs"></div>
        </div>
    </div>

    <script>
        let socket = null;
        let heartbeatTimer = null;

        const logElement = document.getElementById('logs');
        const btnConnect = document.getElementById('btnConnect');
        const btnDisconnect = document.getElementById('btnDisconnect');
        const btnHeartbeat = document.getElementById('btnHeartbeat');
        const btnClearLogs = document.getElementById('btnClearLogs');
        const btnSendPrivate = document.getElementById('btnSendPrivate');
        const btnSendHall = document.getElementById('btnSendHall');
        const btnSendTeam = document.getElementById('btnSendTeam');
        const btnSendCustom = document.getElementById('btnSendCustom');

        function addLog(message, type = 'info') {
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry ${type}`;
            logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            logElement.appendChild(logEntry);
            logElement.scrollTop = logElement.scrollHeight;
        }

        function updateButtonStates(connected) {
            btnConnect.disabled = connected;
            btnDisconnect.disabled = !connected;
            btnHeartbeat.disabled = !connected;
            btnSendPrivate.disabled = !connected;
            btnSendHall.disabled = !connected;
            btnSendTeam.disabled = !connected;
            btnSendCustom.disabled = !connected;
        }

        function startHeartbeat() {
            const interval = parseInt(document.getElementById('heartbeatInterval').value, 10);
            stopHeartbeat(); // 先清除旧的计时器
            
            heartbeatTimer = setInterval(() => {
                if (socket && socket.readyState === WebSocket.OPEN) {
                    socket.send("PING");
                    addLog("发送心跳: PING", "info");
                }
            }, interval);
            
            addLog(`启动心跳，间隔: ${interval}ms`, "info");
        }

        function stopHeartbeat() {
            if (heartbeatTimer) {
                clearInterval(heartbeatTimer);
                heartbeatTimer = null;
                addLog("停止心跳", "warning");
            }
        }

        btnConnect.addEventListener('click', () => {
            try {
                const wsBaseUrl = document.getElementById('wsUrl').value.trim();
                const userId = document.getElementById('userId').value.trim();
                const teamId = document.getElementById('teamId').value.trim();
                
                // 确保URL不包含双斜杠
                let url = `${wsBaseUrl}/${userId}/${teamId}`;
                url = url.replace(/([^:])\/\//g, '$1/');
                
                addLog(`尝试连接到: ${url}`, "info");
                
                socket = new WebSocket(url);
                
                socket.onopen = function(event) {
                    addLog("WebSocket连接已建立!", "success");
                    updateButtonStates(true);
                    startHeartbeat();
                };
                
                socket.onmessage = function(event) {
                    let msgText = event.data;
                    
                    if (msgText === "pong") {
                        addLog("收到心跳响应: pong", "info");
                        return;
                    }
                    
                    try {
                        // 尝试解析JSON
                        const jsonData = JSON.parse(msgText);
                        addLog(`收到JSON消息: ${JSON.stringify(jsonData, null, 2)}`, "success");
                    } catch (e) {
                        // 如果不是JSON，就当作普通文本
                        addLog(`收到消息: ${msgText}`, "success");
                    }
                };
                
                socket.onclose = function(event) {
                    if (event.wasClean) {
                        addLog(`连接已关闭，代码: ${event.code}, 原因: ${event.reason}`, "warning");
                    } else {
                        addLog("连接异常关闭", "error");
                    }
                    updateButtonStates(false);
                    stopHeartbeat();
                };
                
                socket.onerror = function(error) {
                    addLog(`WebSocket错误: ${JSON.stringify(error)}`, "error");
                    updateButtonStates(false);
                };
            } catch (e) {
                addLog(`连接错误: ${e.message}`, "error");
            }
        });

        btnDisconnect.addEventListener('click', () => {
            if (socket) {
                socket.close();
                socket = null;
                addLog("WebSocket连接已手动关闭", "warning");
                updateButtonStates(false);
                stopHeartbeat();
            }
        });

        btnHeartbeat.addEventListener('click', () => {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.send("PING");
                addLog("手动发送心跳: PING", "info");
            } else {
                addLog("无法发送心跳: 连接未建立", "error");
            }
        });

        btnClearLogs.addEventListener('click', () => {
            logElement.innerHTML = '';
            addLog("日志已清空", "info");
        });

        btnSendPrivate.addEventListener('click', () => {
            if (socket && socket.readyState === WebSocket.OPEN) {
                const userId = document.getElementById('userId').value;
                const toId = document.getElementById('privateMsgTo').value;
                const text = document.getElementById('privateMsg').value;
                
                const message = {
                    fromId: parseInt(userId),
                    toId: parseInt(toId),
                    text: text,
                    chatType: 1, // 私聊
                    teamId: 0
                };
                
                socket.send(JSON.stringify(message));
                addLog(`发送私聊消息: ${JSON.stringify(message)}`, "info");
            } else {
                addLog("无法发送私聊: 连接未建立", "error");
            }
        });

        btnSendHall.addEventListener('click', () => {
            if (socket && socket.readyState === WebSocket.OPEN) {
                const userId = document.getElementById('userId').value;
                const text = document.getElementById('hallMsg').value;
                
                const message = {
                    fromId: parseInt(userId),
                    toId: 0,
                    text: text,
                    chatType: 3, // 大厅聊天
                    teamId: 0
                };
                
                socket.send(JSON.stringify(message));
                addLog(`发送大厅消息: ${JSON.stringify(message)}`, "info");
            } else {
                addLog("无法发送大厅消息: 连接未建立", "error");
            }
        });

        btnSendTeam.addEventListener('click', () => {
            if (socket && socket.readyState === WebSocket.OPEN) {
                const userId = document.getElementById('userId').value;
                const teamId = document.getElementById('teamMsgTeamId').value;
                const text = document.getElementById('teamMsg').value;
                
                const message = {
                    fromId: parseInt(userId),
                    toId: 0,
                    text: text,
                    chatType: 2, // 团队聊天
                    teamId: parseInt(teamId)
                };
                
                socket.send(JSON.stringify(message));
                addLog(`发送团队消息: ${JSON.stringify(message)}`, "info");
            } else {
                addLog("无法发送团队消息: 连接未建立", "error");
            }
        });

        btnSendCustom.addEventListener('click', () => {
            if (socket && socket.readyState === WebSocket.OPEN) {
                try {
                    const customJson = document.getElementById('customJson').value;
                    const message = JSON.parse(customJson);
                    
                    socket.send(JSON.stringify(message));
                    addLog(`发送自定义消息: ${JSON.stringify(message)}`, "info");
                } catch (e) {
                    addLog(`无效的JSON格式: ${e.message}`, "error");
                }
            } else {
                addLog("无法发送自定义消息: 连接未建立", "error");
            }
        });

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            addLog("WebSocket测试工具已加载", "info");
            addLog("请设置连接参数并点击'连接'按钮", "info");
            
            // 自动检测环境并填充URL
            const hostname = window.location.hostname;
            if (hostname === 'localhost' || hostname === '127.0.0.1') {
                document.getElementById('wsUrl').value = 'ws://localhost:8080/websocket';
                addLog("检测到本地环境，已设置本地WebSocket地址", "info");
            } else {
                document.getElementById('wsUrl').value = 'ws://47.109.146.201:6401/websocket';
                addLog("检测到远程环境，已设置穿透WebSocket地址", "info");
            }
        });
    </script>
</body>
</html> 